import axios from 'axios'
import { Loading, Message } from 'element-ui'

axios.defaults.baseURL = window.CONFIG.msgWeb
axios.defaults.timeout = window.CONFIG.timeout

// request interceptor
axios.defaults.headers.post['Content-Type'] = 'application/json;charSet=UTF-8'
axios.defaults.headers.get['Content-Type'] = 'application/json;charSet=UTF-8'
axios.defaults.headers.put['Content-Type'] = 'application/json;charSet=UTF-8'
axios.defaults.headers.delete['Content-Type'] = 'application/json;charSet=UTF-8'
axios.defaults.headers.patch['Content-Type'] = 'application/json;charSet=UTF-8'

// 全局配置axios ，注冊token、
// 请求拦截器
axios.interceptors.request.use(config => {
  // loading 加载
  // startLoading()
  return config
}, err => {
  // endLoading()
  Message.error({
    message: '请求超时'
  })
  return Promise.reject(err)
})

// 响应拦截器：
// 1、每次请求结束后，都要更新token值，用于处理登录超时的情况
// 2、响应失败，给全局提示
axios.interceptors.response.use(response => {
  try {
    // endLoading()
    return response
  } catch (e) {
    // endLoading()
    return Promise.reject(response)
  }
}, (e) => {
  Message.error({
    message: '响应报错'
  })
  endLoading()
})

var loading
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中......',
    background: 'rgba(250,250,250,0.8)'
  })
}

function endLoading() {
  loading.close()
}
/**
 * get 方法封装
 * @param url
 * @param params
 * @returns {Promise}
 */
export function getApi(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

// /**
//  * post
//  * @param url
//  * @param parmsData
//  * @returns {Promise}
//  */
export function postApi(url, parmsData = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, parmsData)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
        // endLoading()
      })
  })
}

/**
 * delete 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function deleteApi(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

/**
 * put 方法封装
 * @param url
 * @param params
 * @returns {Promise}
 */
export function putApi(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, params).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

/**
 * patch 方法封装
 * @param url
 * @param params
 * @returns {Promise}
 */
export function patchApi(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, params).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
